package com.home.qh.webapp.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.home.qh.model.ExchangeRate;
import com.home.qh.model.Currency;
import com.home.qh.service.ExchangeRateManager;
import com.home.qh.service.CurrencyManager;

@Controller
public class ExchangeRateController {
	private transient final Log log = LogFactory.getLog(ExchangeRateController.class);
	private ExchangeRateManager exchangeRateManager;
	private CurrencyManager currencyManager;

	@Autowired
	private ApplicationContext context;

	@Autowired
	public void setExchangeRateManager(ExchangeRateManager exchangeRateManager) {
		this.exchangeRateManager = exchangeRateManager;
	}

	@Autowired
	public void setCurrencyManager(CurrencyManager currencyManager) {
		this.currencyManager = currencyManager;
	}

	@RequestMapping(value = "/admin/exchangeRateList.*", method = { RequestMethod.GET,
			RequestMethod.POST })
	public ModelAndView listCities(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		if (log.isDebugEnabled()) {
			log.debug("entering 'handleRequest' method...");
		}

		ExchangeRate exchangeRateSearch = new ExchangeRate();
		String paramValue = request.getParameter("name");
		String paramCurrencyValue = request.getParameter("currency");			
		if (paramValue != null && !"".equalsIgnoreCase(paramValue.trim())
				&& !"null".equalsIgnoreCase(paramValue)) {
			//exchangeRateSearch.setAppDate(paramValue);			
		}

		if (paramCurrencyValue != null
				&& !"".equalsIgnoreCase(paramCurrencyValue.trim())
				&& !"null".equalsIgnoreCase(paramCurrencyValue)) {
			Long paramCurrencyId = null;
			try {
				paramCurrencyId = Long.parseLong(paramCurrencyValue);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			if (paramCurrencyId != null) {
				Currency currencySearch = currencyManager.get(paramCurrencyId);			
				exchangeRateSearch.setCurrency(currencySearch);
			}else{
				exchangeRateSearch.setCurrency(null);
			}
			

		}

		ModelAndView view = new ModelAndView("admin/exchangeRateList");
		view.addObject("currencyList", currencyManager.getAll());
		view.addObject("exchangeRateSearch", exchangeRateSearch);

		view.addObject("exchangeRateList",	exchangeRateManager.getExchangeRateByExchangeRate(exchangeRateSearch, null, false, -1, -1));
		return view;

	}

}
